package com.taglab.chic.taglib;

import java.util.concurrent.*;

/**
 * <p>
 *   Variant of the Memoizer with cached results that expire after a defined period.
 * </p>
 *
 * <p>
 *   WARNING: Setting a (very) low expiration period may mean Memoizer.compute never returns!
 * </p>
 *
 * @author Damien Papworth
 */
public class ExpiringMemoizer<A, V> extends Memoizer<A, V> {
  private final long expiration;
  private final TimeUnit unit;

  /**
   * <p>
   *   Construct an ExpiringMemoizer with the specified expiration time.
   * </p>
   *
   * @param computable Task to execute
   * @param expiration Arbitrary time for the result to return before being cancelled
   * @param unit Time unit to use for expiration
   */
  public ExpiringMemoizer(Computable<A, V> computable, long expiration, TimeUnit unit) {
    super(computable);
    this.expiration = expiration;
    this.unit = unit;
  }

  protected FutureTask<V> createTask(Callable<V> callable) {
    return new ExpiringFutureTask<V>(callable, expiration, unit);
  }

}
